package com.cdvtc.flower.web.servlet;

import com.cdvtc.flower.dao.CustomerDao;
import com.cdvtc.flower.dao.impl.CustomerDaoImpl;
import com.cdvtc.flower.model.Customer;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LonginServlet", urlPatterns = "/LonginServlet")
public class LonginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String customer_id_str = request.getParameter("customerId");
        String password = request.getParameter("password");

        // 转换customer_id为整数（如果可能）
        int customer_id = -1; // 初始化一个默认值
        try {
            customer_id = Integer.parseInt(customer_id_str);
        } catch (NumberFormatException e) {
            // 如果customer_id不是整数，则输出错误信息并退出
            out.println("用户ID必须是整数!");
            return;
        }

        // 打印输入值用于调试
        System.out.println("Customer ID: " + customer_id);
        System.out.println("Password: " + password);

        // 实例化CustomerDao并尝试登录
        CustomerDao customerDao = new CustomerDaoImpl();
        Customer customer = customerDao.userLogin(customer_id, password);

        if (customer != null) {
            // 设置当前登录用户昵称到session中
            HttpSession session = request.getSession();
            session.setAttribute("customer", customer.getUser_name()); // 假设Customer类有getNickname()方法
            // 如果用户存在且账号为2024003，则重定向到management.jsp
            if (customer_id == 2024003) {
                request.getSession().setAttribute("customer", customer);
                response.sendRedirect("management.jsp");
            } else {
                // 否则，重定向到index.jsp（或其他通用页面）
                request.getSession().setAttribute("customer", customer);
                response.sendRedirect("index.jsp");
            }
        } else {
            // 如果用户不存在或密码不正确，则输出错误信息
            out.println("用户登陆失败!");
        }
    }
}
